#include <iostream>
#include <stdio.h>
#include <cstring>
#include <cassert>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

using namespace std;


int main()
{
    system("chcp 65001");
   
    int fds[2];
    int n = pipe(fds);
    assert(n == 0);

  
    pid_t id = fork();
    assert(id >= 0);
    if(id == 0)
    {
        
        close(fds[0]);
        const char *s = "我是子进程，我正在给你发消息";
        int cnt = 0;
        while(true)
        {
            cnt++;
            char buffer[1024];
            snprintf(buffer, sizeof buffer,"child->parent say: %s[%d]");
            write(fds[1], buffer, strlen(buffer));
            sleep(1); 
        }

        
        close(fds[1]);
        exit(0);
    }
    
    close(fds[1]);
    
    while(true)
    {
        char buffer[1024];
        ssize_t s=read(fds[0], buffer, sizeof(buffer) - 1);
        if(s > 0) buffer[s] = 0;
        cout << "Get Message#" << buffer <<" | my pid:"<< getpid() << endl;
    }
    n = waitpid(id, nullptr, 0);
    assert(n == id);
    
    cout << "fds[0]:" << fds[0] << endl;
    cout << "fds[1]:" << fds[0] << endl;
    return 0;
}
